package com.ruibang.glass.file.service.impl;

import com.itextpdf.html2pdf.HtmlConverter;
import com.ruibang.glass.file.service.ExportService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;

@Service
public class ExportServiceImpl implements ExportService {

    @Override
    public void exportToPdf(String htmlContent, HttpServletResponse response, String fileName) {
        try {
            // Set response headers
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
            
            // Convert HTML to PDF using iText
            HtmlConverter.convertToPdf(
                new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8)),
                response.getOutputStream()
            );
            
        } catch (Exception e) {
            throw new RuntimeException("Failed to export PDF: " + e.getMessage());
        }
    }

    @Override
    public void exportToWord(String htmlContent, HttpServletResponse response, String fileName) {
        try {
            // Set response headers
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".docx");

            // Parse HTML content
            Document doc = Jsoup.parse(htmlContent);
            
            // Create Word document
            XWPFDocument document = new XWPFDocument();
            
            // Convert HTML to Word format
            // Note: This is a simplified conversion. You may need more complex logic
            // depending on your HTML structure
            document.createParagraph().createRun().setText(doc.text());
            
            // Write to response
            document.write(response.getOutputStream());
            
        } catch (Exception e) {
            throw new RuntimeException("Failed to export Word document: " + e.getMessage());
        }
    }
} 